struct input
{
	float4 position 			: POSITION;
	float2 texCoord				: TEXCOORD0;
	float2 bumpCoord			: TEXCOORD1;
	float3 objectSpacePosition	: TEXCOORD2;
	float3 normal				: TEXCOORD3;
};

float3 applyBumpMap(
			  float2 bumpCoords,
			  float3 oldNormal,
			  sampler2D bumpMap,
			  float2 mapSizeInv)
{
	float3 normal = oldNormal;
	
	
	float3 bumpMapUnit				= float3(mapSizeInv, 0.0);
	float3 distortion;
	distortion.x 					= tex2D(bumpMap, bumpCoords - bumpMapUnit.xz).r
				  					- tex2D(bumpMap, bumpCoords + bumpMapUnit.xz).r;
	distortion.y 					= tex2D(bumpMap, bumpCoords - bumpMapUnit.zy).r
									- tex2D(bumpMap, bumpCoords + bumpMapUnit.zy).r;
	distortion.z					= 0.0;
	
	return normalize(normal + distortion);
}

float4 main(  input IN,
			  uniform float4x4 modelViewInv,
	          uniform float3 lightPosition[8],
	          uniform float3 Ia[8],
	          uniform float3 Id[8],
	          uniform float3 Is[8],
              uniform float3 Ka,
              uniform float3 Kd,
              uniform float3 Ks,
              uniform float  shininess,
              sampler2D texture,
              sampler2D bumpMap,
              float2 bumpMapSize) : COLOR
{
	float4 color = float4(0.0, 0.0, 0.0, 0.0);
	
	float3 normal			= applyBumpMap(
									IN.bumpCoord,
									IN.normal,
									bumpMap,
									1.0/bumpMapSize);
	
	float3 lightPosObjectSpace[8];
	for (int i = 0; i < 8; i++)
	{
		lightPosObjectSpace[i] = mul(modelViewInv, lightPosition[i]);
	}
	
	float4 eyePositionHom	= mul(modelViewInv, float4(0.0, 0.0, 0.0, 1.0));
	float3 eyePosition		= eyePositionHom.xyz/eyePositionHom.w;
	float3 toEye			= normalize(eyePosition - IN.objectSpacePosition);
	for (int i = 0; i < 8; i++)
	{
		float3 toLight		= normalize(lightPosObjectSpace[i] - IN.objectSpacePosition); 
		float3 halfway		= normalize(toEye + toLight);
		float4 colorVals	= lit(dot(normal, toLight), dot(normal, halfway), shininess);
		
		color.xyz		   += colorVals.x*Ia[i]*Ka	// Ambient part
							+ colorVals.y*Id[i]*Kd	// Diffuse part
							+ colorVals.z*Is[i]*Ks;	// Specular part
	}
	
	color.a = 1.0;
	
	color *= tex2D(texture, IN.texCoord);
	
	return color;
}